from django.shortcuts import render

# Create your views here.
from django.http import HttpResponse
import requests
import time
from bs4 import BeautifulSoup
import re
import json
import urllib


#返回结果格式
def resultData():
    data = {
        "websiteType" : 0,
        "titleName":"",
        "titleHref": "",
        "source":"",
        "label":"",
        "volume":"",
        "summary":"",
        "detailId":'',
        "publishTime" :"",
        "category" : "",
        "quote" :"",
        "abstract": "",
        "doi": "",
        "downLoad": "",
        "keyword": [],
        "author": [],

    }
    return data

def formData(response):
    allData = []
    # 获取sid并且更新返回
    soup = BeautifulSoup(response.text, "html5lib")



    lis = soup.select("r1")

    for li in lis:
        tempData = resultData()

        try:
            tempData["titleName"] = li.select("km")[0].text.strip()
        except:
            pass
        try:
            tempData["titleHref"] = "http://ipub.exuezhe.com/qk.html?DH=" + li.select("dh")[0].text
        except:
            pass


        allData.append(tempData)

    return allData

def getData(keyword):


    headers = {
        'Accept-Encoding': 'gzip, deflate',
        'Accept-Language': 'zh-CN,zh;q=0.9,en;q=0.8',
        'User-Agent': 'Mozilla/5.0 (Macintosh; Intel Mac OS X 10_14_0) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/71.0.3578.98 Safari/537.36',
        'Proxy-Authorization': 'Basic cWY6cWYzLjE0MTU=',
        'Accept': '*/*',
        'Referer': 'http://ipub.exuezhe.com/qk.html?s0=0&s1=%E7%A0%94%E7%A9%B6',
        'Proxy-Connection': 'keep-alive',
    }

    params = (
        ('keyword', keyword),
    )

    response = requests.get('http://ipub.exuezhe.com/Qk/SimpleSearch', headers=headers, params=params)

    response.encoding = "utf-8"

    allData = formData(response)


    return allData


def index(request):

    data = json.loads(request.POST.get('data', '1'))

    # cookies = getOnoCookies()
    allData = getData(data["values"][0])

    return HttpResponse(json.dumps({
        "collection": allData,
        "allNum": 0
    }), content_type="application/json")